class APIClient {
    /**
     * API客户端，负责与后端API进行通信
     */
    constructor(baseUrl = '/api') {
        this.baseUrl = baseUrl;
        this.sessionId = localStorage.getItem('chat_session_id') || null;
        this.requests = new Map(); // 存储请求控制器，用于取消请求
    }
    
    /**
     * 设置会话ID并保存到本地存储
     * @param {string} sessionId - 会话ID
     */
    setSessionId(sessionId) {
        this.sessionId = sessionId;
        if (sessionId) {
            localStorage.setItem('chat_session_id', sessionId);
        } else {
            localStorage.removeItem('chat_session_id');
        }
    }
    
    /**
     * 创建取消请求的控制器
     * @param {string} key - 请求标识
     * @returns {AbortController} - 取消控制器
     */
    _createAbortController(key) {
        // 如果已有相同请求，取消它
        if (this.requests.has(key)) {
            this.requests.get(key).abort();
        }
        
        const controller = new AbortController();
        this.requests.set(key, controller);
        return controller;
    }
    
    /**
     * 移除请求控制器
     * @param {string} key - 请求标识
     */
    _removeAbortController(key) {
        this.requests.delete(key);
    }
    
    /**
     * 创建新会话
     * @param {string} agentName - 代理名称
     * @param {string} agentDescription - 代理描述
     * @param {string} modelName - 模型名称
     * @param {number} temperature - 温度参数
     * @returns {Promise<Object>} - 包含会话ID的响应
     */
    async createSession(agentName, agentDescription, modelName = "gpt-3.5-turbo", temperature = 0.7) {
        const key = `create_session_${agentName}_${modelName}`;
        
        try {
            // 创建取消控制器
            const controller = this._createAbortController(key);
            
            const response = await fetch(`${this.baseUrl}/create-session`, {
                method: 'POST',
                signal: controller.signal,
                body: new URLSearchParams({
                    agent_name: agentName,
                    agent_description: agentDescription,
                    model_name: modelName,
                    temperature: temperature
                }),
                headers: {
                    'Accept': 'application/json'
                }
            });
            
            // 移除控制器
            this._removeAbortController(key);
            
            if (!response.ok) {
                const error = await this._parseErrorResponse(response);
                throw new Error(error.message || `创建会话失败: ${response.statusText}`);
            }
            
            const data = await response.json();
            this.setSessionId(data.session_id);
            return data;
        } catch (error) {
            this._removeAbortController(key);
            
            // 处理取消请求的情况
            if (error.name !== 'AbortError') {
                console.error('创建会话失败:', error);
            }
            throw error;
        }
    }
    
    /**
     * 上传文档
     * @param {File} file - 要上传的文件
     * @returns {Promise<Object>} - 上传结果
     */
    async uploadDocument(file) {
        if (!this.sessionId) {
            throw new Error('没有有效的会话ID，请先创建会话');
        }
        
        const key = `upload_${this.sessionId}_${file.name}_${file.size}`;
        
        try {
            // 创建取消控制器
            const controller = this._createAbortController(key);
            
            const formData = new FormData();
            formData.append('session_id', this.sessionId);
            formData.append('file', file);
            
            const response = await fetch(`${this.baseUrl}/upload-document`, {
                method: 'POST',
                signal: controller.signal,
                body: formData
            });
            
            // 移除控制器
            this._removeAbortController(key);
            
            if (!response.ok) {
                const error = await this._parseErrorResponse(response);
                throw new Error(error.message || `上传文档失败: ${response.statusText}`);
            }
            
            const data = await response.json();
            return data;
        } catch (error) {
            this._removeAbortController(key);
            
            if (error.name !== 'AbortError') {
                console.error('上传文档失败:', error);
            }
            throw error;
        }
    }
    
    /**
     * 发送消息并处理流式响应
     * @param {string} message - 要发送的消息
     * @param {function} onMessage - 接收消息的回调函数
     * @returns {Promise<void>}
     */
    async sendMessage(message, onMessage) {
        if (!this.sessionId) {
            throw new Error('没有有效的会话ID，请先创建会话');
        }
        
        if (!message.trim()) {
            throw new Error('消息内容不能为空');
        }
        
        const key = `chat_${this.sessionId}_${message.substring(0, 30)}`;
        
        try {
            // 创建取消控制器
            const controller = this._createAbortController(key);
            
            const formData = new FormData();
            formData.append('session_id', this.sessionId);
            formData.append('message', message);
            
            const response = await fetch(`${this.baseUrl}/chat`, {
                method: 'POST',
                signal: controller.signal,
                body: formData
            });
            
            if (!response.ok) {
                this._removeAbortController(key);
                const error = await this._parseErrorResponse(response);
                throw new Error(error.content || `发送消息失败: ${response.statusText}`);
            }
            
            // 处理流式响应
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let buffer = '';
            
            while (true) {
                const { done, value } = await reader.read();
                if (done) break;
                
                // 解码数据
                buffer += decoder.decode(value, { stream: true });
                const lines = buffer.split('\n');
                
                // 处理完整的行
                for (let i = 0; i < lines.length - 1; i++) {
                    const line = lines[i].trim();
                    if (line) {
                        try {
                            const data = JSON.parse(line);
                            onMessage(data);
                        } catch (parseError) {
                            console.error('解析流式响应失败:', parseError, '原始数据:', line);
                            onMessage({
                                status: 'error',
                                content: '接收消息时发生错误'
                            });
                        }
                    }
                }
                
                // 保留不完整的行
                buffer = lines[lines.length - 1];
            }
            
            this._removeAbortController(key);
        } catch (error) {
            this._removeAbortController(key);
            
            if (error.name !== 'AbortError') {
                console.error('发送消息失败:', error);
                onMessage({
                    status: 'error',
                    content: error.message || '发送消息时发生错误'
                });
            } else {
                onMessage({
                    status: 'aborted',
                    content: '请求已取消'
                });
            }
            throw error;
        }
    }
    
    /**
     * 清除会话历史
     * @returns {Promise<Object>} - 操作结果
     */
    async clearHistory() {
        if (!this.sessionId) {
            throw new Error('没有有效的会话ID');
        }
        
        const key = `clear_${this.sessionId}`;
        
        try {
            // 创建取消控制器
            const controller = this._createAbortController(key);
            
            const response = await fetch(`${this.baseUrl}/clear-history`, {
                method: 'POST',
                signal: controller.signal,
                body: new URLSearchParams({
                    session_id: this.sessionId
                })
            });
            
            this._removeAbortController(key);
            
            if (!response.ok) {
                const error = await this._parseErrorResponse(response);
                throw new Error(error.message || `清除历史失败: ${response.statusText}`);
            }
            
            return await response.json();
        } catch (error) {
            this._removeAbortController(key);
            
            if (error.name !== 'AbortError') {
                console.error('清除历史失败:', error);
            }
            throw error;
        }
    }
    
    /**
     * 删除会话
     * @returns {Promise<Object>} - 操作结果
     */
    async deleteSession() {
        if (!this.sessionId) {
            throw new Error('没有有效的会话ID');
        }
        
        const key = `delete_${this.sessionId}`;
        
        try {
            // 创建取消控制器
            const controller = this._createAbortController(key);
            
            const response = await fetch(`${this.baseUrl}/delete-session`, {
                method: 'POST',
                signal: controller.signal,
                body: new URLSearchParams({
                    session_id: this.sessionId
                })
            });
            
            this._removeAbortController(key);
            
            if (!response.ok) {
                const error = await this._parseErrorResponse(response);
                throw new Error(error.message || `删除会话失败: ${response.statusText}`);
            }
            
            const data = await response.json();
            this.setSessionId(null);
            return data;
        } catch (error) {
            this._removeAbortController(key);
            
            if (error.name !== 'AbortError') {
                console.error('删除会话失败:', error);
            }
            throw error;
        }
    }
    
    /**
     * 获取会话信息
     * @returns {Promise<Object>} - 会话信息
     */
    async getSessionInfo() {
        if (!this.sessionId) {
            throw new Error('没有有效的会话ID');
        }
        
        const key = `info_${this.sessionId}`;
        
        try {
            // 创建取消控制器
            const controller = this._createAbortController(key);
            
            const response = await fetch(`${this.baseUrl}/session-info?session_id=${this.sessionId}`, {
                signal: controller.signal
            });
            
            this._removeAbortController(key);
            
            if (!response.ok) {
                const error = await this._parseErrorResponse(response);
                throw new Error(error.message || `获取会话信息失败: ${response.statusText}`);
            }
            
            return await response.json();
        } catch (error) {
            this._removeAbortController(key);
            
            if (error.name !== 'AbortError') {
                console.error('获取会话信息失败:', error);
            }
            throw error;
        }
    }
    
    /**
     * 解析错误响应
     * @param {Response} response - 响应对象
     * @returns {Promise<Object>} - 解析后的错误信息
     */
    async _parseErrorResponse(response) {
        try {
            const data = await response.json();
            return data;
        } catch (error) {
            // 如果响应不是JSON格式
            return {
                message: await response.text() || response.statusText
            };
        }
    }
    
    /**
     * 取消所有请求
     */
    cancelAllRequests() {
        this.requests.forEach(controller => {
            controller.abort();
        });
        this.requests.clear();
    }
    
    /**
     * 取消特定请求
     * @param {string} key - 请求标识
     */
    cancelRequest(key) {
        if (this.requests.has(key)) {
            this.requests.get(key).abort();
            this.requests.delete(key);
        }
    }
}

export default APIClient;    